import React, { useState, useEffect } from 'react';
import { Trash2, Plus, TestTube, Settings, FolderOpen } from 'lucide-react';
import { useToast } from '../contexts/ToastContext';

interface PathMappingRule {
  hostPath: string;
  containerPath: string;
  description?: string;
  enabled: boolean;
}

interface PathMappingConfig {
  isDocker: boolean;
  projectRoot: string;
  fallbackHostRoots: string[];
  customMappings: PathMappingRule[];
  settings: {
    enableCustomMappings: boolean;
    strictMode: boolean;
    logMappings: boolean;
  };
  defaultMappings: PathMappingRule[];
}

interface TestResult {
  hostPath: string;
  mappedPath: string;
  isValid: boolean;
  isDocker: boolean;
}

const PathMappingManager: React.FC = () => {
  const [config, setConfig] = useState<PathMappingConfig | null>(null);
  const [loading, setLoading] = useState(true);
  const [newMapping, setNewMapping] = useState({
    hostPath: '',
    containerPath: '/projects',
    description: ''
  });
  const [testPath, setTestPath] = useState('');
  const [testResult, setTestResult] = useState<TestResult | null>(null);
  const [showSettings, setShowSettings] = useState(false);
  const { showToast } = useToast();

  // 显示消息
  const showMessage = (type: 'success' | 'error', text: string) => {
    showToast({ type, text });
  };

  // 加载配置
  const loadConfig = async () => {
    try {
      const response = await fetch('/api/path-mapping/config');
      const data = await response.json();
      if (data.success) {
        setConfig(data.data);
      } else {
        showMessage('error', '加载配置失败: ' + data.error);
      }
    } catch (error) {
      showMessage('error', '加载配置失败');
      console.error('加载配置失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 添加自定义映射
  const addCustomMapping = async () => {
    if (!newMapping.hostPath.trim()) {
      showMessage('error', '请输入宿主机路径');
      return;
    }

    try {
      const response = await fetch('/api/path-mapping/custom', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(newMapping)
      });
      
      const data = await response.json();
      if (data.success) {
        showMessage('success', '自定义映射添加成功');
        setNewMapping({ hostPath: '', containerPath: '/projects', description: '' });
        loadConfig(); // 重新加载配置
      } else {
        showMessage('error', '添加失败: ' + data.error);
      }
    } catch (error) {
      showMessage('error', '添加失败');
      console.error('添加自定义映射失败:', error);
    }
  };

  // 删除自定义映射
  const removeCustomMapping = async (hostPath: string) => {
    try {
      const response = await fetch('/api/path-mapping/custom', {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ hostPath })
      });
      
      const data = await response.json();
      if (data.success) {
        showMessage('success', '映射删除成功');
        loadConfig(); // 重新加载配置
      } else {
        showMessage('error', '删除失败: ' + data.error);
      }
    } catch (error) {
      showMessage('error', '删除失败');
      console.error('删除自定义映射失败:', error);
    }
  };

  // 测试路径映射
  const testPathMapping = async () => {
    if (!testPath.trim()) {
      showMessage('error', '请输入要测试的路径');
      return;
    }

    try {
      const response = await fetch('/api/path-mapping/test', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ hostPath: testPath })
      });
      
      const data = await response.json();
      if (data.success) {
        setTestResult(data.data);
      } else {
        showMessage('error', '测试失败: ' + data.error);
      }
    } catch (error) {
      showMessage('error', '测试失败');
      console.error('测试路径映射失败:', error);
    }
  };

  // 更新设置
  const updateSettings = async (newSettings: any) => {
    try {
      const response = await fetch('/api/path-mapping/settings', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(newSettings)
      });
      
      const data = await response.json();
      if (data.success) {
        showMessage('success', '设置更新成功');
        loadConfig(); // 重新加载配置
      } else {
        showMessage('error', '更新失败: ' + data.error);
      }
    } catch (error) {
      showMessage('error', '更新失败');
      console.error('更新设置失败:', error);
    }
  };

  useEffect(() => {
    loadConfig();
  }, []);

  if (loading) {
    return (
      <div className="flex justify-center items-center h-64">
        <div className="text-neutral-600">加载中...</div>
      </div>
    );
  }

  if (!config) {
    return (
      <div className="text-center text-red-500 p-8">
        <div className="text-lg font-medium">加载配置失败</div>
      </div>
    );
  }

  return (
    <div className="space-y-6 p-6">

      {/* 环境信息 */}
      <div className="bg-white rounded-xl shadow-medium border border-neutral-200">
        <div className="bg-gradient-to-r from-primary-50 to-primary-100 px-6 py-4 border-b border-neutral-200 rounded-t-xl">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 bg-primary-500 rounded-xl flex items-center justify-center shadow-medium">
              <FolderOpen className="h-4 w-4 text-white" />
            </div>
            <h3 className="text-lg font-semibold text-neutral-900">Docker 环境信息</h3>
          </div>
        </div>
        <div className="p-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label className="block text-sm font-medium text-neutral-700 mb-2">运行环境</label>
              <div className={`text-sm font-medium ${
                config.isDocker ? 'text-green-600' : 'text-orange-600'
              }`}>
                {config.isDocker ? 'Docker 容器' : '本地环境'}
              </div>
            </div>
            <div>
              <label className="block text-sm font-medium text-neutral-700 mb-2">项目根目录</label>
              <div className="text-sm font-mono bg-neutral-100 px-3 py-2 rounded-lg">{config.projectRoot}</div>
            </div>
          </div>
          
          {config.fallbackHostRoots.length > 0 && (
            <div className="mt-6">
              <label className="block text-sm font-medium text-neutral-700 mb-2">后备映射根目录</label>
              <div className="space-y-2">
                {config.fallbackHostRoots.map((root, index) => (
                  <div key={index} className="text-sm font-mono bg-neutral-100 px-3 py-2 rounded-lg">{root}</div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>

      {/* 设置 */}
      <div className="bg-white rounded-xl shadow-medium border border-neutral-200">
        <div className="bg-gradient-to-r from-primary-50 to-primary-100 px-6 py-4 border-b border-neutral-200 rounded-t-xl">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="w-8 h-8 bg-primary-500 rounded-xl flex items-center justify-center shadow-medium">
                <Settings className="h-4 w-4 text-white" />
              </div>
              <h3 className="text-lg font-semibold text-neutral-900">映射设置</h3>
            </div>
            <button
              onClick={() => setShowSettings(!showSettings)}
              className="px-4 py-2 text-sm font-medium text-neutral-700 bg-white border border-neutral-300 rounded-lg hover:bg-neutral-50 transition-colors"
            >
              {showSettings ? '隐藏' : '显示'}
            </button>
          </div>
        </div>
        {showSettings && (
          <div className="p-6 space-y-6">
            <div className="flex items-center justify-between">
              <div>
                <label className="block text-sm font-medium text-neutral-700">启用自定义映射</label>
                <div className="text-sm text-neutral-600">允许使用自定义路径映射规则</div>
              </div>
              <label className="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  checked={config.settings.enableCustomMappings}
                  onChange={(e) => 
                    updateSettings({ ...config.settings, enableCustomMappings: e.target.checked })
                  }
                  className="sr-only peer"
                />
                <div className="w-11 h-6 bg-neutral-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-neutral-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-600"></div>
              </label>
            </div>
            
            <div className="flex items-center justify-between">
              <div>
                <label className="block text-sm font-medium text-neutral-700">严格模式</label>
                <div className="text-sm text-neutral-600">保持完整的相对路径结构</div>
              </div>
              <label className="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  checked={config.settings.strictMode}
                  onChange={(e) => 
                    updateSettings({ ...config.settings, strictMode: e.target.checked })
                  }
                  className="sr-only peer"
                />
                <div className="w-11 h-6 bg-neutral-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-neutral-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-600"></div>
              </label>
            </div>
            
            <div className="flex items-center justify-between">
              <div>
                <label className="block text-sm font-medium text-neutral-700">记录映射日志</label>
                <div className="text-sm text-neutral-600">在控制台输出路径映射信息</div>
              </div>
              <label className="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  checked={config.settings.logMappings}
                  onChange={(e) => 
                    updateSettings({ ...config.settings, logMappings: e.target.checked })
                  }
                  className="sr-only peer"
                />
                <div className="w-11 h-6 bg-neutral-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-neutral-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-600"></div>
              </label>
            </div>
          </div>
        )}
      </div>

      {/* 自定义映射管理 */}
      <div className="bg-white rounded-xl shadow-medium border border-neutral-200">
        <div className="bg-gradient-to-r from-primary-50 to-primary-100 px-6 py-4 border-b border-neutral-200 rounded-t-xl">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 bg-primary-500 rounded-xl flex items-center justify-center shadow-medium">
              <Plus className="h-4 w-4 text-white" />
            </div>
            <h3 className="text-lg font-semibold text-neutral-900">自定义路径映射</h3>
          </div>
        </div>
        <div className="p-6 space-y-6">
          {/* 添加新映射 */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label className="block text-sm font-medium text-neutral-700 mb-2">宿主机路径</label>
              <input
                type="text"
                placeholder="例如: /Users/project1"
                value={newMapping.hostPath}
                onChange={(e) => setNewMapping({ ...newMapping, hostPath: e.target.value })}
                className="w-full px-3 py-2 border border-neutral-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-neutral-700 mb-2">容器路径</label>
              <input
                type="text"
                placeholder="例如: /projects"
                value={newMapping.containerPath}
                onChange={(e) => setNewMapping({ ...newMapping, containerPath: e.target.value })}
                className="w-full px-3 py-2 border border-neutral-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-neutral-700 mb-2">描述</label>
              <input
                type="text"
                placeholder="可选描述"
                value={newMapping.description}
                onChange={(e) => setNewMapping({ ...newMapping, description: e.target.value })}
                className="w-full px-3 py-2 border border-neutral-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
              />
            </div>
          </div>
          
          <button
            onClick={addCustomMapping}
            className="w-full px-4 py-3 bg-gradient-to-r from-primary-600 to-primary-700 text-white rounded-lg hover:from-primary-700 hover:to-primary-800 focus:outline-none focus:ring-2 focus:ring-primary-500 transition-all duration-300 flex items-center justify-center gap-2 font-medium shadow-medium hover:shadow-strong"
          >
            <Plus className="h-4 w-4" />
            添加映射
          </button>

          {/* 现有映射列表 */}
          {config.customMappings.length > 0 && (
            <div className="space-y-4">
              <label className="block text-sm font-medium text-neutral-700">现有自定义映射</label>
              {config.customMappings.map((mapping, index) => (
                <div key={index} className="flex items-center justify-between p-4 border border-neutral-200 rounded-lg bg-neutral-50">
                  <div className="flex-1">
                    <div className="font-mono text-sm text-neutral-900">
                      {mapping.hostPath} → {mapping.containerPath}
                    </div>
                    {mapping.description && (
                      <div className="text-xs text-neutral-600 mt-1">{mapping.description}</div>
                    )}
                  </div>
                  <button
                    onClick={() => removeCustomMapping(mapping.hostPath)}
                    className="ml-4 p-2 text-red-600 hover:text-red-700 hover:bg-red-50 rounded-lg transition-colors"
                    title="删除映射"
                  >
                    <Trash2 className="h-4 w-4" />
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* 路径测试 */}
      <div className="bg-white rounded-xl shadow-medium border border-neutral-200">
        <div className="bg-gradient-to-r from-primary-50 to-primary-100 px-6 py-4 border-b border-neutral-200 rounded-t-xl">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 bg-primary-500 rounded-xl flex items-center justify-center shadow-medium">
              <TestTube className="h-4 w-4 text-white" />
            </div>
            <h3 className="text-lg font-semibold text-neutral-900">路径映射测试</h3>
          </div>
        </div>
        <div className="p-6 space-y-4">
          <div className="flex gap-3">
            <input
              type="text"
              placeholder="输入要测试的宿主机路径"
              value={testPath}
              onChange={(e) => setTestPath(e.target.value)}
              className="flex-1 px-3 py-2 border border-neutral-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
            />
            <button
              onClick={testPathMapping}
              className="px-6 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors font-medium"
            >
              测试
            </button>
          </div>
          
          {testResult && (
            <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
              <div className="space-y-2 text-sm">
                <div><strong className="text-neutral-700">宿主机路径:</strong> <code className="bg-white px-2 py-1 rounded text-neutral-900">{testResult.hostPath}</code></div>
                <div><strong className="text-neutral-700">映射路径:</strong> <code className="bg-white px-2 py-1 rounded text-neutral-900">{testResult.mappedPath}</code></div>
                <div><strong className="text-neutral-700">路径有效:</strong> 
                  <span className={testResult.isValid ? 'text-green-600 font-medium' : 'text-red-600 font-medium'}>
                    {testResult.isValid ? ' ✓ 有效' : ' ✗ 无效'}
                  </span>
                </div>
                <div><strong className="text-neutral-700">Docker环境:</strong> <span className="font-medium">{testResult.isDocker ? '是' : '否'}</span></div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* 使用说明 */}
      <div className="bg-white rounded-xl shadow-medium border border-neutral-200">
        <div className="bg-gradient-to-r from-primary-50 to-primary-100 px-6 py-4 border-b border-neutral-200 rounded-t-xl">
          <h3 className="text-lg font-semibold text-neutral-900">使用说明</h3>
        </div>
        <div className="p-6">
          <div className="text-sm text-neutral-600 space-y-4">
            <div>
              <p className="font-medium text-neutral-800 mb-2">添加自定义映射:</p>
              <ul className="list-disc list-inside space-y-1 ml-4">
                <li>宿主机路径必须是绝对路径（如 /Users/project1 或 C:\\Projects）</li>
                <li>容器路径默认为 /projects，可以自定义</li>
                <li>描述字段可选，用于标识映射用途</li>
              </ul>
            </div>
            
            <div>
              <p className="font-medium text-neutral-800 mb-2">Docker Compose 配置:</p>
              <p className="mb-2">添加映射后，需要在 docker-compose.yml 中添加对应的 volumes 配置：</p>
              <pre className="bg-neutral-100 p-3 rounded-lg text-xs font-mono overflow-x-auto">
{`volumes:
  - "/Users/project1:/projects/project1"`}
              </pre>
            </div>
            
            <div>
              <p className="font-medium text-neutral-800 mb-2">映射优先级:</p>
              <ul className="list-disc list-inside space-y-1 ml-4">
                <li>自定义映射（按路径长度排序，最长匹配优先）</li>
                <li>后备映射（系统默认的常见路径）</li>
                <li>默认映射（取路径最后一部分作为项目名）</li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default PathMappingManager;